﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Abp.Runtime.Caching;
using AutoMapper.QueryableExtensions;
using FwProject.Authorization.Users;
using FwProject.Core.Restaurant;
using FwProject.Manager;
using FwProject.Restaurant.Dto;
using FwProject.Users;
using FwProject.Users.Dto;
using X.PagedList;
using Microsoft.AspNetCore.Hosting;
using Abp.AutoMapper;
using System.Linq.Expressions;
using FwProject.PublicService.SqlExec;
using Abp.UI;
using FwProject.Core.SettlementInfoModel;
using FwProject.PrePaymentInfo;
using FwProject.Distribution;
using Microsoft.AspNetCore.Identity;
using FwProject.Core.TypeNumber;

namespace FwProject.Restaurant
{
    [AbpAuthorize]
    public class RestaurantAppService : FwProjectAppServiceBase, IRestaurantAppService
    {
        public readonly IRepository<RestaurantInfo, Guid> _repositoryRestaurantInfo;
        public readonly IRepository<User, long> _repositoryUser;
        public readonly IRestaurantUserAppService _iRestaurantUserAppService;
        public readonly IUserAppService _iuserAppService;
        private readonly UserManager _userManager;
        private readonly RestaurantInfoManager _restaurantManager;
        public readonly ICacheManager _catchmanager;
        public readonly IHostingEnvironment _hostingEnvironment;
        private readonly ISqlExecuter _sqlExecuter;
        public readonly IRepository<RestaurantTypenNumberInfo, Guid> _restaurantTypenNumberInfo;
        public readonly IRepository<TypeNumberInfo, Guid> _restaurantTypeNumber;

        public readonly IRepository<RestaurantUserInfo, Guid> _repositoryRestaurantUserInfo;
        public readonly IRepository<SettlementInfo, Guid> _repositorySettlementInfo;

        public readonly IRepository<PrePaymentInfoModel, Guid> _repositoryPrePaymentInfoModel;

        private readonly IRepository<DriverLine, Guid> _repositoryLoadDriverLine;

        private readonly IRepository<SettlementAccount, Guid> _repositorySettlementAccount;

        private readonly IRepository<DepositInfo, Guid> _repositoryDepositInfo;

        private readonly RestaurantTypeNumberInfoManager _restaurantTypeNumberInfoManager;

        private readonly IPasswordHasher<User> _passwordHasher;
        private readonly UserRegistrationManager _userRegistrationManager;

        public IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }
        public RestaurantAppService(
            ICacheManager catchmanager, IRepository<User, long> repositoryUser,
            IRepository<RestaurantInfo, Guid> repositoryRestaurantInfo, RestaurantInfoManager restaurantManager,
            IRestaurantUserAppService iRestaurantUserAppService,
            UserManager userManager, IUserAppService iuserAppService, IHostingEnvironment hostingEnvironment,
            IRepository<RestaurantTypenNumberInfo, Guid> restaurantTypenNumberInfo,
             IRepository<RestaurantUserInfo, Guid> repositoryRestaurantUserInfo,
             ISqlExecuter sqlExecuter,
             IRepository<SettlementInfo, Guid> repositorySettlementInfo,
             IRepository<PrePaymentInfoModel, Guid> repositoryPrePaymentInfoModel,
             IRepository<DriverLine, Guid> repositoryLoadDriverLine,
             RestaurantTypeNumberInfoManager restaurantTypeNumberInfoManager,
             IPasswordHasher<User> passwordHasher,
             UserRegistrationManager userRegistrationManager,
             IRepository<TypeNumberInfo, Guid> restaurantTypeNumber,
             IRepository<SettlementAccount, Guid> repositorySettlementAccount,
             IRepository<DepositInfo, Guid> repositoryDepositInfo)
        {

            _sqlExecuter = sqlExecuter;
            _hostingEnvironment = hostingEnvironment;
            _userManager = userManager;
            _catchmanager = catchmanager;
            _repositoryUser = repositoryUser;
            _repositoryRestaurantInfo = repositoryRestaurantInfo;
            _restaurantManager = restaurantManager;
            _iRestaurantUserAppService = iRestaurantUserAppService;
            _iuserAppService = iuserAppService;
            _restaurantTypenNumberInfo = restaurantTypenNumberInfo;
            _repositoryRestaurantUserInfo = repositoryRestaurantUserInfo;
            _repositorySettlementInfo = repositorySettlementInfo;
            _guid = SequentialGuidGenerator.Instance;
            _repositoryPrePaymentInfoModel = repositoryPrePaymentInfoModel;
            _repositoryLoadDriverLine = repositoryLoadDriverLine;

            _restaurantTypeNumberInfoManager = restaurantTypeNumberInfoManager;
            _passwordHasher = passwordHasher;
            _userRegistrationManager = userRegistrationManager;
            _repositorySettlementAccount = repositorySettlementAccount;
            _restaurantTypeNumber = restaurantTypeNumber;
            _repositoryDepositInfo = repositoryDepositInfo;
        }

        /// <summary>
        /// 添加一个餐厅
        /// </summary>
        /// <returns>The create.</returns>
        /// <param name="input">Input.</param>
        public async Task<Guid> Create(RestaurantInputDto input)
        {
            var types = input.TypenNumberInfos.Select(o => o.TypeNumberId);
            if (types.Distinct().Count() != types.Count())
                throw new UserFriendlyException(2, "不能添加重复的型号！！！");

            var user = await _repositoryUser.GetAsync(input.EmployeeDriverid);
            var model = _map.Map<RestaurantInfo>(input);
            model.FactoryinfoId = user.FactoryinfoId;
            model.Id = _guid.Create();
            model.Thump = SaveFile(_hostingEnvironment.WebRootPath, input.Thump, RestaurantInfo.TempFileUrlPrefix, RestaurantInfo.SaveFileUrlPrefix, $"{DateTime.Now.ToString("yyyyMMdd")}/");
            model.Character = FontHelper.GetSpellCode(model.RestaurantName);

            if (input.TypenNumberInfos != null)
            {
                List<RestaurantTypenNumberInfo> list = new List<RestaurantTypenNumberInfo>();
                foreach (var item in input.TypenNumberInfos)
                {
                    try
                    {
                        if (item.TypeNumberId != Guid.Empty && item.Price > 0)
                        {
                            RestaurantTypenNumberInfo typeinfo = new RestaurantTypenNumberInfo()
                            {
                                Id = _guid.Create(),
                                Price = item.Price,
                                TypeNumberId = item.TypeNumberId,
                                FactoryinfoId = user.FactoryinfoId
                            };
                            list.Add(typeinfo);
                        }
                    }
                    catch (Exception)
                    {

                        throw;
                    }

                }
                model.RestaurantTypenNumberInfos = list;
            }

            //if (model.RestaurantTypenNumberInfos.Count > 0)
            //{
            //    foreach (var item in model.RestaurantTypenNumberInfos)
            //    {
            //        if (item.TypeNumberId != Guid.Empty && item.Price > 0)
            //        {
            //            item.Id = Guid.NewGuid();
            //        }
            //        else
            //        {
            //            model.RestaurantTypenNumberInfos.Remove(item);
            //        }
            //    }
            //}
            Guid id = await _restaurantManager.CreateRestaurant(model);

            if (!string.IsNullOrWhiteSpace(input.RestaurantUserInputs))
            {
                long temp;
                var restaurantIds = input.RestaurantUserInputs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(o => { long.TryParse(o, out temp); return temp; });

                if (restaurantIds.Any())//判断是否有元素
                {
                    foreach (var item in restaurantIds)
                    {
                        await _repositoryRestaurantUserInfo.InsertAsync(new RestaurantUserInfo() { Id = Guid.NewGuid(), EmployeeRestaurantId = item, RestaurantInfoId = id });
                    }

                }
            }

            return id;

        }

        /// <summary>
        /// 获取一条餐厅信息
        /// </summary>
        /// <returns>The by identifier async.</returns>
        /// <param name="id">Identifier.</param>
        public async Task<RestaurantDto> GetByIdAsync(Guid id)
        {
            var model = (await _repositoryRestaurantInfo.GetAllIncluding(o => o.RestaurantTypenNumberInfos).Where(o => o.Id == id).ToListAsync()).FirstOrDefault();
            return _map.Map<RestaurantDto>(model);
        }



        /// <summary>
        /// 获取一条餐厅信息(输入)
        /// </summary>
        /// <returns>The by identifier async.</returns>
        /// <param name="id">Identifier.</param>
        public async Task<RestaurantInputDto> GetByEnterIdAsync(Guid id)
        {
            var model = (await GetCache).AsQueryable().Where(o => o.Id == id).FirstOrDefault();
            var dname = model.EmployeeDriver.Name;
            var dto = _map.Map<RestaurantInputDto>(model);
            dto.DriveridName = dname;
            var types = _restaurantTypenNumberInfo.GetAll().Where(o => o.Restaurantid == id && o.IsDefault == true).MapTo<List<RestaurantInputDto.TypeNumberDto>>();
            dto.TypenNumberInfos = types;
            dto.RestaurantUsers = await _iRestaurantUserAppService.GetAllByRetaurantAsync(id);

            return dto;
        }

        /// <summary>
        /// 获取餐厅列表
        /// </summary>
        /// <returns>The restaurant paged list async.</returns>
        /// <param name="pageIdx">Page index.</param>
        public async Task<IList<AppRestaurantDto>> GetPagedListAsync(string Restaurantname, DateTime? begindateTime, DateTime? enddatetime)
        {
            var model = GetAppRestaurantDtoCache.Where(o => o.IsDiscontinuation == 0);

            if (!string.IsNullOrEmpty(Restaurantname))
                model = model.Where(o => o.RestaurantName.Contains(Restaurantname)).ToList();

            if (begindateTime != null)
                model = model.Where(o => o.CreationTime >= begindateTime).ToList();

            if (enddatetime != null)
                model = model.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24)).ToList();

            return await model.Where(o => o.EmployeeDriverid == AbpSession.UserId.Value).OrderByDescending(m => m.CreationTime).ToListAsync();
        }
        public async Task<IPagedList<RestaurantOutputDto>> GetAllPagedListAsync(int pageIdx, int pageSize, string factoryid, string keyword, long? DriverId, Guid? LineId)
        {
            var listmodel = (await GetCache).AsQueryable();/* _repositoryRestaurantInfo.GetAllIncluding(o => o.RestaurantTypenNumberInfos);*/
            if (!string.IsNullOrWhiteSpace(factoryid))
            {
                Guid fid = new Guid(factoryid);
                listmodel = listmodel.Where(o => o.FactoryinfoId == fid);
            }
            if (!string.IsNullOrWhiteSpace(keyword))
                listmodel = listmodel.Where(o => o.RestaurantName.Contains(keyword));

            if (DriverId.HasValue)
                listmodel = listmodel.Where(o => o.EmployeeDriverid == DriverId.Value);

            if (LineId.HasValue)
            {
                var lineUsers = _repositoryLoadDriverLine.GetAll().Where(o => o.LineId == LineId).Select(o => o.DriverId);
                listmodel = listmodel.Where(o => lineUsers.Any(s => s == o.EmployeeDriverid));
            }


            //var reuser = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser);
            var data = listmodel.ProjectTo<RestaurantOutputDto>();

            //var data = listmodel.GroupJoin(reuser, l => l.Id, u => u.RestaurantInfoId, (l1, u1) => new RestaurantOutputDto()
            //{
            //    Id = l1.Id,
            //    RestaurantName = l1.RestaurantName,
            //    RestaurantAddress = l1.RestaurantAddress,
            //    CreationTime = l1.CreationTime,
            //    RestaurantContacts = u1.Select(o => o.EmployeeRestauranUser.Name),
            //    RestaurantPhone = u1.Select(o => o.EmployeeRestauranUser.Mobile),
            //    ChargeWay = l1.ChargeWay,
            //    BalanceWay = l1.BalanceWay,
            //    BalanceCycle = l1.BalanceCycle,
            //    DriverId = l1.EmployeeDriverid,
            //    DriverName = l1.EmployeeDriver.Name,
            //    IsDiscontinuation = l1.IsDiscontinuation,
            //    DiscontinuationTime = l1.DiscontinuationTime,
            //    Deposit = l1.Deposit,
            //    DepositDate = l1.DepositDate
            //});



            var model = await data.OrderByDescending(o => o.CreationTime).ToPagedListAsync(pageIdx, pageSize);

            return model;
        }
        /// <summary>
        /// 获取已停用的餐厅列表
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<RestaurantOutputDto>> GetDiscontinuationPagedListAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            var listmodel = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == usermodel.FactoryinfoId && o.IsDiscontinuation == true);/* _repositoryRestaurantInfo.GetAllIncluding(o => o.RestaurantTypenNumberInfos);*/
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.DiscontinuationTime >= beginTime);
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.DiscontinuationTime <= endTime.Value.AddHours(24));

            //var reuser = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser);
            var data = listmodel.ProjectTo<RestaurantOutputDto>();
            //var data = listmodel.GroupJoin(reuser, l => l.Id, u => u.RestaurantInfoId, (l1, u1) => new RestaurantOutputDto()
            //{
            //    Id = l1.Id,
            //    RestaurantName = l1.RestaurantName,
            //    RestaurantAddress = l1.RestaurantAddress,
            //    CreationTime = l1.CreationTime,
            //    RestaurantContacts = u1.Select(o => o.EmployeeRestauranUser.Name),
            //    RestaurantPhone = u1.Select(o => o.EmployeeRestauranUser.Mobile),
            //    ChargeWay = l1.ChargeWay,
            //    BalanceWay = l1.BalanceWay,
            //    BalanceCycle = l1.BalanceCycle,
            //    DriverName = l1.EmployeeDriver.Name,
            //    IsDiscontinuation = l1.IsDiscontinuation,
            //    DiscontinuationTime = l1.DiscontinuationTime,
            //    Deposit = l1.Deposit,
            //    DepositDate = l1.DepositDate
            //});

            var model = await data.OrderByDescending(o => o.DiscontinuationTime).ToPagedListAsync(pageIdx, pageSize);

            return model;
        }
        /// <summary>
        /// 餐厅新增统计
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="pageSize"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<IPagedList<RestaurantOutputDto>> GetNewAddPagedListAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            var listmodel = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == usermodel.FactoryinfoId);/* _repositoryRestaurantInfo.GetAllIncluding(o => o.RestaurantTypenNumberInfos);*/
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime >= beginTime);
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            //var reuser = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser);
            var data = listmodel.ProjectTo<RestaurantOutputDto>();
            //var data = listmodel.GroupJoin(reuser, l => l.Id, u => u.RestaurantInfoId, (l1, u1) => new RestaurantOutputDto()
            //{
            //    Id = l1.Id,
            //    RestaurantName = l1.RestaurantName,
            //    RestaurantAddress = l1.RestaurantAddress,
            //    CreationTime = l1.CreationTime,
            //    RestaurantContacts = u1.Select(o => o.EmployeeRestauranUser.Name),
            //    RestaurantPhone = u1.Select(o => o.EmployeeRestauranUser.Mobile),
            //    ChargeWay = l1.ChargeWay,
            //    BalanceWay = l1.BalanceWay,
            //    BalanceCycle = l1.BalanceCycle,
            //    DriverName = l1.EmployeeDriver.Name,
            //    IsDiscontinuation = l1.IsDiscontinuation,
            //    DiscontinuationTime = l1.DiscontinuationTime,
            //    Deposit = l1.Deposit,
            //    DepositDate = l1.DepositDate
            //});

            var model = await data.OrderByDescending(o => o.CreationTime).ToPagedListAsync(pageIdx, pageSize);

            return model;
        }
        /// <summary>
        /// 获取所有的餐厅列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<RestaurantOutputDto>> GetRestaurantListAsync()
        {
            var listmodel = (await GetCache).AsQueryable();

            //var reuser = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser);
            var data = listmodel.ProjectTo<RestaurantOutputDto>();
            //var data = listmodel.GroupJoin(reuser, l => l.Id, u => u.RestaurantInfoId, (l1, u1) => new RestaurantOutputDto()
            //{
            //    Id = l1.Id,
            //    RestaurantName = l1.RestaurantName,
            //    RestaurantAddress = l1.RestaurantAddress,
            //    CreationTime = l1.CreationTime,
            //    RestaurantContacts = u1.Select(o => o.EmployeeRestauranUser.Name),
            //    RestaurantPhone = u1.Select(o => o.EmployeeRestauranUser.Mobile),
            //    ChargeWay = l1.ChargeWay,
            //    BalanceWay = l1.BalanceWay,
            //    BalanceCycle = l1.BalanceCycle,
            //    DriverName = l1.EmployeeDriver.Name,
            //    IsDiscontinuation = l1.IsDiscontinuation,
            //    DiscontinuationTime = l1.DiscontinuationTime,
            //    Deposit = l1.Deposit,
            //    DepositDate = l1.DepositDate
            //});
            var model = await data.OrderByDescending(o => o.CreationTime).ToListAsync();

            return model;
        }

        public async Task<List<RestaurantOutputDto>> GetRestaurantByDriverIdAsync(long driverId)
        {
            var listmodel = (await GetCache).Where(o => o.EmployeeDriverid == driverId).AsQueryable();

            //var reuser = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser);
            var data = listmodel.ProjectTo<RestaurantOutputDto>();
            //var data = listmodel.GroupJoin(reuser, l => l.Id, u => u.RestaurantInfoId, (l1, u1) => new RestaurantOutputDto()
            //{
            //    Id = l1.Id,
            //    RestaurantName = l1.RestaurantName,
            //    RestaurantAddress = l1.RestaurantAddress,
            //    CreationTime = l1.CreationTime,
            //    RestaurantContacts = u1.Select(o => o.EmployeeRestauranUser.Name),
            //    RestaurantPhone = u1.Select(o => o.EmployeeRestauranUser.Mobile),
            //    ChargeWay = l1.ChargeWay,
            //    BalanceWay = l1.BalanceWay,
            //    BalanceCycle = l1.BalanceCycle,
            //    DriverName = l1.EmployeeDriver.Name,
            //    IsDiscontinuation = l1.IsDiscontinuation,
            //    DiscontinuationTime = l1.DiscontinuationTime,
            //    Deposit = l1.Deposit,
            //    DepositDate = l1.DepositDate
            //});


            var model = await data.OrderByDescending(o => o.CreationTime).ToListAsync();

            return model;
        }
        /// <summary>
        /// 获取所有新增的餐厅
        /// </summary>
        /// <returns></returns>
        public async Task<List<RestaurantOutputDto>> GetRestaurantNewAddAsync(DateTime? beginTime, DateTime? endTime)
        {
            var listmodel = (await GetCache).AsQueryable();
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime >= beginTime);
            if (endTime.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            //var reuser = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser);
            var data = listmodel.ProjectTo<RestaurantOutputDto>();
            //var data = listmodel.GroupJoin(reuser, l => l.Id, u => u.RestaurantInfoId, (l1, u1) => new RestaurantOutputDto()
            //{
            //    Id = l1.Id,
            //    RestaurantName = l1.RestaurantName,
            //    RestaurantAddress = l1.RestaurantAddress,
            //    CreationTime = l1.CreationTime,
            //    RestaurantContacts = u1.Select(o => o.EmployeeRestauranUser.Name),
            //    RestaurantPhone = u1.Select(o => o.EmployeeRestauranUser.Mobile),
            //    ChargeWay = l1.ChargeWay,
            //    BalanceWay = l1.BalanceWay,
            //    BalanceCycle = l1.BalanceCycle,
            //    DriverName = l1.EmployeeDriver.Name,
            //    IsDiscontinuation = l1.IsDiscontinuation,
            //    DiscontinuationTime = l1.DiscontinuationTime,
            //    Deposit = l1.Deposit,
            //    DepositDate = l1.DepositDate
            //});


            var model = await data.OrderByDescending(o => o.CreationTime).ToListAsync();

            return model;
        }

        public async Task<List<RestaurantOutputDto>> GetDiscontinuationListAsync(DateTime? beginTime, DateTime? endTime)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            var listmodel = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == usermodel.FactoryinfoId && o.IsDiscontinuation == true);
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.DiscontinuationTime >= beginTime);
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.DiscontinuationTime <= endTime.Value.AddHours(24));

            //var reuser = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser);
            var data = listmodel.ProjectTo<RestaurantOutputDto>();
            //var data = listmodel.GroupJoin(reuser, l => l.Id, u => u.RestaurantInfoId, (l1, u1) => new RestaurantOutputDto()
            //{
            //    Id = l1.Id,
            //    RestaurantName = l1.RestaurantName,
            //    RestaurantAddress = l1.RestaurantAddress,
            //    CreationTime = l1.CreationTime,
            //    RestaurantContacts = u1.Select(o => o.EmployeeRestauranUser.Name),
            //    RestaurantPhone = u1.Select(o => o.EmployeeRestauranUser.Mobile),
            //    ChargeWay = l1.ChargeWay,
            //    BalanceWay = l1.BalanceWay,
            //    BalanceCycle = l1.BalanceCycle,
            //    DriverName = l1.EmployeeDriver.Name,
            //    IsDiscontinuation = l1.IsDiscontinuation,
            //    DiscontinuationTime = l1.DiscontinuationTime,
            //    Deposit = l1.Deposit,
            //    DepositDate = l1.DepositDate
            //});

            var model = await data.OrderByDescending(o => o.DiscontinuationTime).ToListAsync();

            return model;
        }

        /// <summary>
        /// 获取未分配工厂的餐厅列表
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IPagedList<RestaurantDto>> GetRestaurantPagedListAsync(int pageIdx, int pageSize, string restaurantName)
        {
            var listmodel = (await GetCache).AsQueryable();

            if (!string.IsNullOrEmpty(restaurantName))
            {
                listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));
            }
            return await listmodel.Where(o => o.FactoryinfoId == null).OrderByDescending(o => o.CreationTime).ProjectTo<RestaurantDto>().ToPagedListAsync(pageIdx, pageSize);
        }


        public async Task EditRestaurantInfo(RestaurantModelDto input)
        {
            var user = _repositoryUser.Get(input.UserId);
            user.Mobile = input.PhoneNumber;
            user.PhoneNumber = input.PhoneNumber;
            user.Name = input.Name;

            var RestaurantUser = await _iRestaurantUserAppService.GetByUserRestaurant(input.UserId);
            var restaurantmodel = _repositoryRestaurantInfo.GetAll().Where(o => o.Id == RestaurantUser.RestaurantInfoId).FirstOrDefault();
            restaurantmodel.RestaurantName = input.RestaurantName;
            restaurantmodel.RestaurantAddress = input.Address;
            restaurantmodel.Character = FontHelper.GetSpellCode(input.RestaurantName);
            await _userManager.UpdateAsync(user);
            await _restaurantManager.UpdateRestaurant(restaurantmodel);
        }

        public async Task EditRestaurantByFactory(Guid id, Guid FactoryInfoId)
        {
            var model = await _repositoryRestaurantInfo.GetAsync(id);
            model.FactoryinfoId = FactoryInfoId;
            await _restaurantManager.UpdateRestaurant(model);
        }
        /// <summary>
        /// 修改餐厅信息
        /// </summary>
        /// <returns>The update.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="input">Input.</param>
        public async Task Update(Guid id, RestaurantInputDto input)
        {
            if (input.TypenNumberInfos != null)
            {
                var types = input.TypenNumberInfos.Select(o => o.TypeNumberId);
                if (types.Distinct().Count() != types.Count())
                    throw new UserFriendlyException(2, "不能添加重复的型号！！！");
            }
            var model = await _repositoryRestaurantInfo.GetAsync(id);
            var originalBalanceWayEnum = model.BalanceWay;
            var originalThump = model.Thump;
            var originalStock = model.Stock;
            

            model = _map.Map(input, model);

            //实际店存
            model.RealStock += model.Stock - originalStock;


            if (model.BalanceWay != originalBalanceWayEnum)
            {
                var settlement = _repositorySettlementInfo.GetAll().Where(o => o.Restaurantid == model.Id && o.ReceiptInfoId.HasValue == false).Any();

                if (settlement)
                    throw new UserFriendlyException(2, "该餐厅还有未收款的收据，无法更改结算方式！！！");
            }

            if (input.IsDiscontinuation == true)
            {
                model.DiscontinuationTime = DateTime.Now;
            }
            else
            {
                model.DiscontinuationTime = null;
            }
            model.Stock = input.Stock;
            model.StockTime = DateTime.Now;
            model.Thump = base.SaveFile(_hostingEnvironment.WebRootPath, input.Thump, RestaurantInfo.TempFileUrlPrefix, RestaurantInfo.SaveFileUrlPrefix, $"{DateTime.Now.ToString("yyyyMMdd")}/", originalThump);
            model.Character = FontHelper.GetSpellCode(input.RestaurantName);
            model.RemarkContent = input.RemarkContent;
            long temp;
            var restaurantIds = input.RestaurantUserInputs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(o => { long.TryParse(o, out temp); return temp; });
            var rus = await _repositoryRestaurantUserInfo.GetAll().Where(o => o.RestaurantInfoId == model.Id).ToListAsync();
            if (restaurantIds.Any())
            {
                if (rus.Count > 0)
                {
                    //获取新型号与原型号之间的差异数据
                    var removes = rus.Where(o => restaurantIds.Any(r => r == o.EmployeeRestaurantId) == false).ToList();
                    Expression<Func<RestaurantUserInfo, bool>> fun = f => removes.Any(s => s.Id == f.Id);
                    if (removes?.Count > 0)//判断是否有修改
                        for (int i = 0; i < removes.Count; i++)//执行删除操作
                            await _repositoryRestaurantUserInfo.DeleteAsync(removes[i]);
                }
                var adds = restaurantIds.Where(r => rus.Any(o => o.EmployeeRestaurantId == r) == false);
                if (adds.Count() != 0)
                {
                    foreach (var a in adds)
                        await _repositoryRestaurantUserInfo.InsertAsync(new RestaurantUserInfo { Id = Guid.NewGuid(), RestaurantInfoId = model.Id, EmployeeRestaurantId = a });
                }
            }
            else
            {
                if (rus.Count > 0)
                {
                    for (int i = 0; i < rus.Count; i++)//执行删除操作
                        await _repositoryRestaurantUserInfo.DeleteAsync(rus[i]);
                }
            }
            //型号
            if (input.TypenNumberInfos != null)
            {
                if (input.TypenNumberInfos.Any())
                {
                    var typeNumbers = input.TypenNumberInfos;
                    var originalTypenumber = _restaurantTypenNumberInfo.GetAll().Where(o => o.Restaurantid == model.Id).ToList();
                    if (originalTypenumber.Count > 0)
                    {
                        var removes = originalTypenumber.Where(o => typeNumbers.Any(r => r.Id == o.Id) == false).ToList();
                        if (removes?.Count > 0)//判断是否有修改
                        {
                            for (int i = 0; i < removes.Count; i++)//执行删除操作
                            {
                                removes[i].IsDefault = false;
                                await _restaurantTypenNumberInfo.UpdateAsync(removes[i]);
                            }

                        }
                    }
                    var adds = typeNumbers.Where(r => originalTypenumber.Any(o => o.Id == r.Id) == false);

                    if (adds.Count() > 0)
                    {
                        foreach (var a in adds)
                        {
                            RestaurantTypenNumberInfo info = new RestaurantTypenNumberInfo() { Id = Guid.NewGuid(), TypeNumberId = a.TypeNumberId, Restaurantid = model.Id, Price = a.Price, FactoryinfoId = (await GetCurrentUserAsync()).FactoryinfoId };
                            await _restaurantTypeNumberInfoManager.CreateRestaurantTypeNumber(info);
                        }
                    }


                    var updates = typeNumbers.Where(r => originalTypenumber.Any(o => o.Id == r.Id) == true);
                    foreach (var item in updates)
                    {
                        RestaurantTypeNumberInput rtinput = new RestaurantTypeNumberInput()
                        {
                            TypeNumberId = item.TypeNumberId.Value,
                            IsDefault = true,
                            Restaurantid = model.Id,
                            Price = item.Price,
                            FactoryinfoId = (await _iuserAppService.GetByIdUserAsync(AbpSession.UserId.Value)).FactoryinfoId
                        };
                        var data = await _restaurantTypenNumberInfo.GetAsync(item.Id);
                        data = _map.Map(rtinput, data);
                        await _restaurantTypenNumberInfo.UpdateAsync(data);
                    }
                    //for (int x = 0; x < typeNumbers.Count; x++)
                    //{
                    //    RestaurantTypeNumberInput rtinput = new RestaurantTypeNumberInput()
                    //    {
                    //        TypeNumberId = typeNumbers[x].TypeNumberId.Value,
                    //        IsDefault = true,
                    //        Restaurantid = model.Id,
                    //        Price = typeNumbers[x].Price,
                    //        FactoryinfoId = (await _iuserAppService.GetByIdUserAsync(AbpSession.UserId.Value)).FactoryinfoId
                    //    };
                    //    var data = await _restaurantTypenNumberInfo.GetAsync(typeNumbers[x].Id);
                    //    data = _map.Map(rtinput, data);
                    //    await _restaurantTypenNumberInfo.UpdateAsync(data);
                    //}

                }
            }
            await _restaurantManager.UpdateRestaurant(model);
        }
        #region  App店存修改
        /// <summary>
        /// App店存修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="stock"></param>
        /// <returns></returns>
        public async Task EditStock(Guid id, int stock)
        {
            var model = await _repositoryRestaurantInfo.GetAsync(id);
            model.Stock = stock;
            model.StockTime = DateTime.Now;
            await _restaurantManager.UpdateRestaurant(model);
        }
        #endregion
        public async Task DeleteAsync(Guid id)
        {
            var entity = await _repositoryRestaurantInfo.GetAsync(id);
            await _repositoryRestaurantInfo.DeleteAsync(entity);
        }

        public async Task<IPagedList<RestaurantDto>> GetUnassignedsAsync(int pageIdx, int pageSize, string keyword)
        {
            var query = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == null);
            if (!string.IsNullOrWhiteSpace(keyword))
                query = query.Where(o => o.RestaurantName.Contains(keyword));

            var model = await query.ProjectTo<RestaurantDto>().ToPagedListAsync(pageIdx, pageSize);

            foreach (var item in model)
            {
                var user = await _iRestaurantUserAppService.GetOneUser(item.Id);
                if (user != null)
                    item.User = _map.Map<RestaurantUser>(user.EmployeeRestauranUser);
                else
                    item.User = new RestaurantUser();
            }


            return model;
        }
        /// <summary>
        /// 获取没收押金的餐厅列表
        /// </summary>
        public async Task<IPagedList<RestaurantDto>> GetCollectDepositListAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, string restaurantName)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            var listmodel = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == usermodel.FactoryinfoId);

            if (!string.IsNullOrEmpty(restaurantName))
                listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.DepositDate >= beginTime);
            if (endTime.HasValue)
                listmodel = listmodel.Where(o => o.DepositDate <= endTime.Value.AddHours(24));

            return await listmodel.Where(o => o.Deposit == 0).ProjectTo<RestaurantDto>().ToPagedListAsync(pageIdx, pageSize);
        }
        ///// <summary>
        ///// 收押金导出
        ///// </summary>
        //public async Task<List<ExportCollectDepositDto>> GetExportCollectDepositListAsync(string restaurantName)
        //{
        //    var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
        //    string sql = $@"select RestaurantName,RestaurantAddress,Deposit,DepositDate from RestaurantInfo where Deposit=0.00 and FactoryinfoId='{usermodel.FactoryinfoId}'";
        //    var listmodel = _sqlExecuter.FromDapperSqlQuery<ExportCollectDepositDto>(sql, null).AsQueryable();

        //    if (!string.IsNullOrEmpty(restaurantName))
        //        listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));
        //    return listmodel.ToList();
        //}
        ///// <summary>
        ///// 退押金导出
        ///// </summary>
        //public async Task<List<ExportCollectDepositDto>> GetExportReturnDepositListAsync(string restaurantName, DateTime? beginTime, DateTime? endTime)
        //{
        //    var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
        //    string sql = $@"select RestaurantName,RestaurantAddress,Deposit,DepositDate from RestaurantInfo where Deposit>0 and FactoryinfoId='{usermodel.FactoryinfoId}'";
        //    var listmodel = _sqlExecuter.FromDapperSqlQuery<ExportCollectDepositDto>(sql, null).AsQueryable();

        //    if (!string.IsNullOrEmpty(restaurantName))
        //        listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));
        //    if (beginTime.HasValue)
        //        listmodel = listmodel.Where(o => o.DepositDate >= beginTime);
        //    if (endTime.HasValue)
        //        listmodel = listmodel.Where(o => o.DepositDate <= endTime.Value.AddHours(24));

        //    return listmodel.ToList();
        //}

        public async Task EditDeposit(Guid id, decimal deposit)
        {
            var model = await _repositoryRestaurantInfo.GetAsync(id);
            model.Deposit = deposit;
            model.DepositDate = DateTime.Now;
            await _restaurantManager.UpdateRestaurant(model);
        }
        public async Task ReturnDeposit(Guid id, decimal money)
        {
            var model = await _repositoryRestaurantInfo.GetAsync(id);
            model.Deposit = model.Deposit - money;
            model.DepositDate = DateTime.Now;

            //DepositInput input = new DepositInput()
            //{
            //    FactoryinfoId = model.FactoryinfoId.Value,
            //    RestaurantId = model.Id,
            //    Money = deposit,
            //    DepositType = DepositType.退押金
            //};
            //await _depositAppService.Create(input);
            await _restaurantManager.UpdateRestaurant(model);
        }
        /// <summary>
        /// 获取已收押金的餐厅列表
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="pageSize"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<List<RestaurantDto>> GetReturnDepositListAsync()
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            var listmodel = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == usermodel.FactoryinfoId);

            return await listmodel.Where(o => o.Deposit > 0).ProjectTo<RestaurantDto>().ToListAsync();
        }

        /// <summary>
        /// 餐厅排名查看
        /// </summary>
        /// <returns></returns>
        public List<AppTopRestaurantDto> GetTopRestaurant()
        {

            return GetTopCatch;
        }

        public async Task<List<RestaurantDistributedDto>> GetRestaurantDistributedAsync(Guid? id, string keyword)
        {
            if (!id.HasValue)
            {
                var user = await base.GetCurrentUserAsync();
                id = user.FactoryinfoId;
            }

            var query = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == id);

            if (!string.IsNullOrWhiteSpace(keyword))
                query = query.Where(o => o.RestaurantName.Contains(keyword));

            return query.OrderByDescending(m => m.CreationTime).ProjectTo<RestaurantDistributedDto>().ToList();
        }

        public async Task<List<RestaurantAdvancePaymentDto>> GetRestaurantAdvancePaymentAsync(Guid? id)
        {
            if (!id.HasValue)
            {
                var user = await base.GetCurrentUserAsync();
                id = user.FactoryinfoId;
            }
            var query = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == id)
                .GroupJoin(_repositoryPrePaymentInfoModel.GetAll().Where(o => o.PrePaymentInfoType == PrePaymentInfoType.收预交金 && o.PrePaymentInfoStatus == PrePaymentInfoStatus.已审核).Select(o => new { o.RestaurantInfoId, o.PrePaymentPrice, o.PrePaymentInfoType })
                .Union(_repositoryPrePaymentInfoModel.GetAll().Where(o => o.PrePaymentInfoType == PrePaymentInfoType.退预交金 && o.PrePaymentInfoStatus == PrePaymentInfoStatus.已审核).Select(o => new { o.RestaurantInfoId, o.PrePaymentPrice, o.PrePaymentInfoType })), i => i.Id, j => j.RestaurantInfoId, (i, j) => new
                {
                    Id = i.Id,
                    RestaurantName = i.RestaurantName,
                    AdvancePayment = j.Where(o => o.PrePaymentInfoType == PrePaymentInfoType.收预交金).Sum(o => o.PrePaymentPrice) - j.Where(o => o.PrePaymentInfoType == PrePaymentInfoType.退预交金).Sum(o => o.PrePaymentPrice)
                }).GroupJoin(_repositorySettlementInfo.GetAll().Where(o => o.ExamineStatus == Core.SettlementInfoModel.ExamineStatus.已审核), i => i.Id, j => j.Restaurantid, (i, j) => new RestaurantAdvancePaymentDto
                {
                    Id = i.Id,
                    RestaurantName = i.RestaurantName,
                    AdvancePayment = i.AdvancePayment - j.Sum(o => o.UsePrePayment)
                });

            return query.ToList();

        }


        /// <summary>
        /// 餐厅店存统计
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<RestaurantStockDto>> GetRestaurantStockAsync(int pageIdx, int pageSize, string restaurantName, string driverId)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            #region sql
            //string where = $" and a.FactoryinfoId='{usermodel.FactoryinfoId}' ";
            //if (!string.IsNullOrEmpty(driverId))
            //    where += $" and  a.CreatorUserId={driverId}";
            //if (!string.IsNullOrEmpty(restaurantName))
            //    where += $" and a.RestaurantName like '%{restaurantName}%'";

            //string sql = $@"select RestaurantId,
            //                       a.RestaurantName,
            //                       c.Name,
            //                       c.Mobile,
            //                       d.Stock, d.RealStock as RestaurantStock from V_DistributionInfo a,RestaurantUserInfo b,AbpUsers c,RestaurantInfo d 
            //where a.RestaurantId=b.RestaurantInfoId and b.EmployeeRestaurantId = c.Id and a.RestaurantId=d.Id {where} GROUP BY RestaurantId,a.RestaurantName,d.Stock,d.RealStock,c.Name,c.Mobile ORDER BY d.Stock DESC";

            //var listmodel = await _sqlExecuter.IPagedListDynamicListFromSqlAsync<RestaurantStockDto>(sql, "", pageIdx, pageSize);
            #endregion

            var data = _repositoryRestaurantInfo.GetAll().Where(o => o.FactoryinfoId == usermodel.FactoryinfoId).Select(s => new RestaurantStockDto
            {
                RestaurantId = s.Id,
                DriverId = s.EmployeeDriverid,
                RestaurantName = s.RestaurantName,
                Name = s.RestaurantContact,
                Mobile = s.Mobile,
                Stock = s.Stock,
                RestaurantStock = s.RealStock
            });
            if (!string.IsNullOrEmpty(restaurantName))
                data = data.Where(o => o.RestaurantName.Contains(restaurantName));
            if (!string.IsNullOrEmpty(driverId))
                data = data.Where(o => o.DriverId.ToString() == driverId);

            return await data.ToPagedListAsync(pageIdx, pageSize);
        }
        /// <summary>
        /// 餐厅店存统计导出
        /// </summary>
        public async Task<List<RestaurantStockDto>> GetExportRestaurantStockAsync(string restaurantName, string driverId)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            #region sql
            //string where = $" and a.FactoryinfoId='{usermodel.FactoryinfoId}' ";
            //if (!string.IsNullOrEmpty(driverId))
            //    where += $" and  a.CreatorUserId={driverId}";

            //string sql = $@"select RestaurantId,
            //                       a.RestaurantName,
            //                       c.Name,
            //                       c.Mobile,
            //                      (Sum(Stock)+Sum(Distributioncount)+Sum(Givecount)-Sum(Recoverycount)-Sum(Backboxcount)) as Stock from V_DistributionInfo a,RestaurantUserInfo b,AbpUsers c,RestaurantInfo d 
            //where a.RestaurantId=b.RestaurantInfoId and b.EmployeeRestaurantId = c.Id and a.RestaurantId=d.Id {where} GROUP BY RestaurantId,a.RestaurantName,c.Name,c.Mobile";

            //var listmodel = _sqlExecuter.FromDapperSqlQuery<RestaurantStockDto>(sql, null).AsQueryable();

            //if (!string.IsNullOrEmpty(restaurantName))
            //    listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));
            #endregion

            var data = _repositoryRestaurantInfo.GetAll().Where(o => o.FactoryinfoId == usermodel.FactoryinfoId).Select(s => new RestaurantStockDto
            {
                RestaurantId = s.Id,
                DriverId = s.EmployeeDriverid,
                RestaurantName = s.RestaurantName,
                Name = s.RestaurantContact,
                Mobile = s.Mobile,
                Stock = s.Stock,
                RestaurantStock = s.RealStock
            });
            if (!string.IsNullOrEmpty(restaurantName))
                data = data.Where(o => o.RestaurantName.Contains(restaurantName));
            if (!string.IsNullOrEmpty(driverId))
                data = data.Where(o => o.DriverId.ToString() == driverId);

            return data.ToList();
        }
        /// <summary>
        /// 获取餐厅配送详情
        /// </summary>
        public async Task<IPagedList<RestaurantDistributionDetailsDto>> GetRestaurantDetailsPagedListAsync(int pageIdx, int pageSize, Guid restaurantId, DateTime? beginTime, DateTime? endTime)
        {

            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            string where = $" and b.FactoryinfoId='{usermodel.FactoryinfoId}' ";
            if (beginTime.HasValue)
                where += $" and a.CreationTime>='{beginTime}'";
            if (endTime.HasValue)
                where += $" and a.CreationTime<='{endTime.Value.AddHours(24)}'";

            string sql = $@"select a.CreationTime,
                                    RestaurantName,
                                    Name,
                                    Distributioncount,
                                    (Distributioncount*d.Count) as DistributionBycount,
                                    Recoverycount,
                                    (Recoverycount*d.Count) as RecoveryBycount,
                                    Exchangegoodscount,
                                    (Exchangegoodscount*d.Count) as ExchangegoodsBycount,
                                    Givecount,
                                    (Givecount*d.Count) as GiveBycount,
                                    Damagecount,
                                    Backboxcount,
                                    Backnumbercount,
                                    Price,
                                    Sumprice from DistributionInfoDetails a,RestaurantInfo b,RestaurantTypenNumberInfo c,TypeNumberInfo d where a.Restaurantid = b.Id and a.RestaurantTypenNumberInfoId =c.Id and a.TypeNumberInfoId =d.Id and a.Restaurantid='{restaurantId}'{where} ORDER BY a.CreationTime DESC";
            return await _sqlExecuter.IPagedListDynamicListFromSqlAsync<RestaurantDistributionDetailsDto>(sql, "", pageIdx, pageSize);

        }

        private Task<List<RestaurantInfo>> GetCache
        {
            get
            {
                ICache cache = _catchmanager.GetCache(nameof(RestaurantInfo));
                return cache.GetAsync("list", async () => await _repositoryRestaurantInfo.GetAllIncluding(o => o.RestaurantTypenNumberInfos, o => o.EmployeeDriver).ToListAsync());
            }

        }

        private List<AppRestaurantDto> GetAppRestaurantDtoCache
        {
            get
            {
                var user = _repositoryUser.Get(AbpSession.UserId.Value);
                ICache cache = _catchmanager.GetCache(nameof(AppRestaurantDto));
                return cache.Get($"list_{user.FactoryinfoId}", () => AppRestaurantDtolistCatch(user).ToList());
            }
        }
        private IList<AppRestaurantDto> AppRestaurantDtolistCatch(User user)
        {
            string sql = $@"SELECT [Id]
                          ,[RestaurantAddress]
                          ,[Stock]
                          ,[CreationTime]
                          ,[Character]
                          ,[RestaurantName]
                          ,[longitude]
                          ,[latitude]
                          ,[Thump]
                          ,[DriverName]
                          ,[DriverMobile]
                          ,[FactoryinfoId]
                          ,[EmployeeDriverid]
                          ,[RestaurantUserName]
                          ,[RestaurantUserMobile]
                          ,[flagDistributionInfo]
                          ,[IsDiscontinuation]
                          ,[Distributioncount]
                      FROM  [V_RestauranDistributinfo] where IsDeleted='False' and  FactoryinfoId='{user.FactoryinfoId}'";
            return _sqlExecuter.FromDapperSqlQuery<AppRestaurantDto>(sql, null);
        }


        private List<AppTopRestaurantDto> GetTopCatch
        {
            get
            {
                List<AppTopRestaurantDto> list = new List<AppTopRestaurantDto>();
                try
                {

                    var RestaurantUsermodel = _repositoryRestaurantUserInfo.GetAll().Where(o => o.EmployeeRestaurantId == AbpSession.UserId.Value).FirstOrDefault();
                    if (RestaurantUsermodel == null)
                        throw new UserFriendlyException("未绑定餐厅信息");

                    var Restaurant = _repositoryRestaurantInfo.Get(RestaurantUsermodel.RestaurantInfoId.Value);
                    ICache cache = _catchmanager.GetCache(nameof(AppTopRestaurantDto));
                    list = cache.Get($"list_{Restaurant.Id}", () => AppTopRestaurantDtolistCatch().ToList());
                }
                catch (Exception exe)
                {

                    Logger.Info("餐厅排名不存在", exe);
                }

                return list;
            }

        }
        private IQueryable<AppTopRestaurantDto> AppTopRestaurantDtolistCatch()
        {
            var RestaurantUsermodel = _repositoryRestaurantUserInfo.GetAll().Where(o => o.EmployeeRestaurantId == AbpSession.UserId.Value).FirstOrDefault();
            var Restaurant = _repositoryRestaurantInfo.Get(RestaurantUsermodel.RestaurantInfoId.Value);
            string sql = string.Format($@"select  top 10 isnull(b.Distributioncount,0) Distributioncount ,a.RestaurantName,a.Thump,a.Id  from RestaurantInfo a 
                                    left join (select a.Restaurantid, SUM(b.Distributioncount*c.[Count]) Distributioncount from DistributionInfo a left join DistributionInfoDetails b 
                                    on b.DistributionInfoId=a.Id left join TypeNumberInfo c on c.Id=b.TypeNumberInfoId
                                     group by a.Restaurantid
                                     ) as b on a.Id=b.Restaurantid
                                    where [dbo].[fnGetDistanceNew] ('{Restaurant?.longitude}','{Restaurant?.latitude}',a.longitude,a.latitude)<=3
                                    order by Distributioncount desc");

            return _sqlExecuter.FromSqlQuery<AppTopRestaurantDto>(sql, null);

        }

        #region 餐厅Excel导入
        /// <summary>
        /// 餐厅导入
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ExcelImportRetaurantSuccess> ExcelImportAsync(List<ExcelImportRetaurant> dto, Guid FactoryinfoId)
        {
            var loginUser = await base.GetCurrentUserAsync();
            ExcelImportRetaurantSuccess result = new ExcelImportRetaurantSuccess();
            int i = 0;
            foreach (var o in dto)
            {
                i++;
                o.TypeNumberName = o.TypeNumberName.Trim();
                o.DriverName = o.DriverName.Trim();
                var usermodel = _repositoryUser.GetAll().Where(t => t.Name == o.DriverName && t.FactoryinfoId == FactoryinfoId).FirstOrDefault();
                if (usermodel == null)
                    result.FailureMessage += $"第{i}行司机姓名错误；";
                var typenumber = _restaurantTypeNumber.GetAll().Where(t => t.Name == o.TypeNumberName && t.FactoryinfoId == FactoryinfoId).FirstOrDefault();
                if (typenumber == null)
                    result.FailureMessage += $"，第{i}行型号名称错误；";
                var account = _repositorySettlementAccount.GetAll().Where(t => t.Name == "默认账户" && t.FactoryinfoId == FactoryinfoId).FirstOrDefault();
                if (account == null)
                    result.FailureMessage += $"，第{i}行账户名称错误；";
                try
                {
                    RestaurantInfo entity = new RestaurantInfo()
                    {
                        Id = _guid.Create(),
                        RestaurantName = o.RestaurantName,
                        RestaurantAddress = o.RestaurantAdderss,
                        RestaurantContact = o.RestaurantContact,
                        Mobile = o.Mobile,
                        Deposit = o.Deposit == "" ? 0 : Convert.ToDecimal(o.Deposit),
                        DepositDate = o.DepositDate == "" ? new DateTime?() : Convert.ToDateTime(o.DepositDate),
                        FactoryinfoId = FactoryinfoId,
                        EmployeeDriverid = usermodel.Id,
                        longitude = "106.541133",
                        latitude = "29.844049"

                    };
                    switch (o.ChargeWay)
                    {
                        case "按箱收费":
                            entity.ChargeWay = ChargeWayEnum.按箱收费;
                            break;
                        case "按套收费":
                            entity.ChargeWay = ChargeWayEnum.按套收费;
                            break;
                    }

                    switch (o.BalanceWay)
                    {
                        case "日结":
                            entity.BalanceWay = BalanceWayEnum.日结;
                            break;
                        case "定期结算":
                            entity.BalanceWay = BalanceWayEnum.定期结算;
                            break;
                    }

                    switch (o.BalanceCycle)
                    {
                        case "每周定期":
                            entity.BalanceCycle = BalanceCycleEnum.每周定期;
                            break;
                        case "半月定期":
                            entity.BalanceCycle = BalanceCycleEnum.半月定期;
                            break;
                        case "每月定期":
                            entity.BalanceCycle = BalanceCycleEnum.每月定期;
                            break;
                        case "自定日期":
                            entity.BalanceCycle = BalanceCycleEnum.自定日期;
                            break;
                    }



                    //餐厅负责人
                    var user = await _userRegistrationManager.RegisterAsync(
                        o.RestaurantContact,
                        o.RestaurantContact,
                        $"{DateTime.Now.ToString("yyyyMMddhhmmss")}@123.com",
                        o.Mobile,
                        $"f{o.Mobile}",
                        o.Mobile,
                        FactoryinfoId,
                        true
                    );

                    //餐厅的添加
                    await _repositoryRestaurantInfo.InsertAsync(entity);

                    RestaurantUserInfo retaurantUser = new RestaurantUserInfo()
                    {
                        Id = _guid.Create(),
                        EmployeeRestaurantId = user.Id,
                        RestaurantInfoId = entity.Id,
                    };
                    //餐厅绑定人员录入
                    await _repositoryRestaurantUserInfo.InsertAsync(retaurantUser);

                    RestaurantTypenNumberInfo typeNumber = new RestaurantTypenNumberInfo()
                    {
                        Id = _guid.Create(),
                        FactoryinfoId = FactoryinfoId,
                        Restaurantid = entity.Id,
                        Price = Convert.ToDecimal(o.Price),
                        IsDefault = true,
                        TypeNumberId = typenumber.Id
                    };

                    //餐厅绑定型号
                    await _restaurantTypenNumberInfo.InsertAsync(typeNumber);
                    decimal Deposit = 0m;
                    if (!string.IsNullOrEmpty(o.Deposit) && decimal.TryParse(o.Deposit, out Deposit))
                    {
                        DepositInfo deposit = new DepositInfo()
                        {
                            Id = _guid.Create(),
                            FactoryinfoId = FactoryinfoId,
                            DepositType = DepositType.收押金,
                            DepositStatus = DepositStatus.未提交,
                            Money = Convert.ToDecimal(o.Deposit),
                            DepositTime = Convert.ToDateTime(o.DepositDate),
                            RestaurantId = entity.Id,
                            CapitalAccountId = account.Id,
                            AccountNo = account.Number,
                            AccountName = account.Name,
                            AgentPeoperUserId = loginUser.Id,//经办人为当前登陆人
                            AgentPeoper = loginUser.Name,
                            RemarkContent = "系统导入"
                        };
                        await _repositoryDepositInfo.InsertAsync(deposit);
                    }
                    result.SuccessCount += 1;
                }
                catch (Exception e)
                {
                    result.FailureCount += 1;
                }
            }
            return result;
        }


        #endregion

    }
}
